// Created by lifei on 2020/7/21--14:43.
<template>
  <div class>
    <div v-for="(item, index) in type.split(',')" :key="index">
      <!--图片组件-->
      <template v-if="item==='image'">
        <div class="text-tips mb12" v-if="!hideExplain">{{tips[0]}}</div>
        <div class="upload-media">
          <el-upload
            v-if="!isView"
            :ref="type"
            action="/admin/sys-file/upLodeFileAdd"
            list-type="picture-card"
            :accept="accepts[0]"
            :file-list="imageList"
            :on-change="(file, files) => {handleChange(file, files, item)}"
            :auto-upload="autoUpload"
          >
            <i slot="default" class="el-icon-plus" style="font-size: 16px;">
              <p style="font-size: 8px">图片上传</p>
            </i>
            <div slot="file" slot-scope="{file}">
              <div class="img-box" :style="'background-image:url('+file.url+')'"></div>
              <div class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </div>
            </div>
          </el-upload>
          <!--<div class="mark mb20" v-if="isShowFileList || isView">
                        <div class="flex-c" v-for="(item, index) in loadFileList" :key="index">
                            <template v-if="item.type.split('/')[0] === 'image'" >
                                <div style="border: 1px solid #c0c4cc; margin: 5px 5px 0 0;border-radius: 4px;width: 50px; height: 50px">
                                    <el-image
                                        :src="'/admin/sys-file/img/' + item.fileId"
                                        :preview-src-list="['/admin/sys-file/img/' + item.fileId]">
                                    </el-image>
                                </div>
                                <div class="name mr20">{{ item.original + '(' + (item.fileSize / 1024 / 1024).toFixed(4) + 'M)'}}</div>
                                <div class="date mr20">{{ item.updateTime }}</div>
                                <div class="btn" v-if="!isView">
                                    <el-button type="text" @click="downloadLoadFile(item)">下载</el-button>
                                    <el-button type="text" @click="deleteLoadFile(item)">删除</el-button>
                                    &lt;!&ndash;                            <el-button type="text" @click="view(item)">查看</el-button>&ndash;&gt;
                                </div>
                                <div class="btn" v-else>
                                    <el-button type="text" @click="downloadLoadFile(item)">下载</el-button>
                                </div>
                            </template>

                        </div>
          </div>-->
        </div>
      </template>
      <!--视频组件-->
      <template v-if="item==='video'">
        <div class="text-tips mb12" v-if="!hideExplain">{{tips[1]}}</div>
        <div class="upload-media">
          <el-upload
            v-if="!isView"
            :ref="type"
            action="/admin/sys-file/upLodeFileAdd"
            list-type="picture-card"
            :accept="accepts[1]"
            :file-list="videoList"
            :on-change="(file, files) => {handleChange(file, files, item)}"
            :auto-upload="autoUpload"
          >
            <i slot="default" class="el-icon-plus" style="font-size: 16px;">
              <p style="font-size: 8px">视频上传</p>
            </i>
            <div slot="file" slot-scope="{file}">
              <video class="img-box" preload="metadata" :src="file.url+'#t=3'"></video>
              <div class="el-upload-list__item-actions">
                <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </div>
            </div>
          </el-upload>
          <!-- <div class="mark mb20" v-if="isShowFileList || isView">
                        <div class="flex-c" v-for="(item, index) in loadFileList" :key="index">
                            <template v-if="item.type.split('/')[0] === 'video'" >
                                <div class="name mr20">{{ item.original + '(' + (item.fileSize / 1024 / 1024).toFixed(4) + 'M)'}}</div>
                                <div class="date mr20">{{ item.updateTime }}</div>
                                <div class="btn" v-if="!isView">
                                    <el-button type="text" @click="downloadLoadFile(item)">下载</el-button>
                                    <el-button type="text" @click="deleteLoadFile(item)">删除</el-button>
&lt;!&ndash;                                    <el-button type="text" @click="view(item)">查看</el-button>&ndash;&gt;
                                </div>
                                <div class="btn" v-else>
                                    <el-button type="text" @click="downloadLoadFile(item)">下载</el-button>
                                </div>
                            </template>

                        </div>
          </div>-->
        </div>
      </template>
      <!--文件上传-->
      <template v-if="item==='file'">
        <div class="text-tips mb12" v-if="!hideExplain">{{tips[2]}}</div>
        <div>
          <el-upload
            v-if="!isView"
            style="max-width: 400px;"
            ref="myUpload"
            :action="url"
            :accept="accepts[2]"
            :on-change="(file, files) => {handleChange(file, files, item)}"
            :auto-upload="autoUpload"
            :before-upload="beforeUpload"
            :name="uploadName"
            :with-credentials="withCredentials"
            :file-list="fileList"
            :on-remove="handleRemove"
            multiple
          >
            <div class="upload-text all-center">
              <span class="el-icon-upload2"></span>
              <span>上传文件</span>
            </div>
          </el-upload>
          <!--<div class="mark mb20">
                        <div class="flex-c" v-for="(item, index) in loadFileList" :key="index">
                            <template>
                                <div v-if="item.type.split('/')[0] === 'image'" style="border: 1px solid #c0c4cc; margin: 5px 5px 0 0;border-radius: 4px;width: 50px; height: 50px">
                                    <el-image
                                        :src="'/admin/sys-file/img/' + item.fileId"
                                        :preview-src-list="['/admin/sys-file/img/' + item.fileId]">
                                    </el-image>
                                </div>
                                <div class="name mr20">{{ item.original + '(' + (item.fileSize / 1024 / 1024).toFixed(4) + 'M)'}}</div>
                                <div class="date mr20">{{ item.updateTime }}</div>
                                <div class="btn" v-if="!isView">
                                    <el-button type="text" @click="downloadLoadFile(item)">下载</el-button>
                                    <el-button type="text" @click="deleteLoadFile(item)">删除</el-button>
                                    <el-button type="text" v-if="item.type.split('/')[1] === 'pdf'" @click="viewPdf(item)">预览</el-button>
                                </div>
                                <div class="btn" v-else>
                                    <el-button type="text" @click="downloadLoadFile(item)">下载</el-button>
                                </div>
                            </template>
                        </div>
          </div>-->
        </div>
      </template>
    </div>

    <div class="mark" v-if="isShowFileList || isView">
      <div class="text-tips mb12" v-if="!hideExplain">上传文件列表:</div>
      <div class="flex-c" v-for="(item, index) in loadFileList" :key="index">
        <template>
          <div v-if="item.type.split('/')[0] === 'image'" style="border: 1px solid #c0c4cc; margin: 5px 5px 0 0;border-radius: 4px;width: 50px; height: 50px">
            <el-image style="width: 50px; height: 50px" :src="'/admin/sys-file/img/' + item.fileId" :preview-src-list="['/admin/sys-file/img/' + item.fileId]"></el-image>
          </div>
          <div class="name mr20">{{ item.original + '(' + (item.fileSize / 1024 / 1024).toFixed(4) + 'M)'}}</div>
          <div class="date mr20">{{ item.updateTime }}</div>
          <div class="btn">
            <el-button type="text" @click="downloadLoadFile(item)">下载</el-button>
            <el-button type="text" v-if="item.type.split('/')[1] === 'pdf'" @click="viewPdf(item)">预览</el-button>
            <el-button type="text" v-if="canDelete" @click="deleteLoadFile(item)">删除</el-button>
          </div>
        </template>
      </div>
    </div>

    <div>
      <v-dialog title="预览" :show.sync="pdfDialogVisible" :closeOnClickModal="false" @beforeClose="beforeClose" appendToBody width="1200px">
        <v-pdf v-if="pdfDialogVisible" :fileId="pdfSrc"></v-pdf>
      </v-dialog>
    </div>
  </div>
</template>

<script>
import BaseLoad from '@/assets/vue-mixin/BaseLoad'
import dbl from '@/utils/dbl'
import { getFiles, delFiles, checkFiles } from '@/api/operate-construction-contract'
import vPdf from '@/components/v-pdf'
import { download } from "~/admin/api/common"
import { downloadBlob } from "~/utils/index"
import { IMAGE_LIMIT, VIDEO_LIMIT, FILE_LIMIT, } from '@/assets/js/constant'

export default {
  name: "upload-media",
  mixins: [BaseLoad],
  components: { vPdf },
  props: {
    // hxf-0903-选择文件类型，可选类型，image,video,file
    type: {
      type: String,
      default: ''    // 图片：image   视频：video  文件： file   图片,视频,文件：image,video,file
    },
    // hxf-0801-设置文件大小
    fileSize: {
      type: Number,
      default: 50
    },
    // hxf-0801-设置上传地址
    url: {
      type: String,
      default: '/admin/sys-file/upLodeFileAdd'
    },
    // hxf-0801-设置上传文件接收名字
    uploadName: {
      type: String,
      default: 'file'
    },
    //hxf-0801-设置支持发送cookie凭证信息
    withCredentials: {
      type: Boolean,
      default: false
    },
    //hxf-0801-设置为false不会自动上传，需使用ref手动上传
    autoUpload: {
      type: Boolean,
      default: false
    },
    //hxf-0801-设置请求头部参数
    headers: {
      type: Object,
      default: () => {
        return {
          Authorization: dbl.get('token')
        }
      }
    },
    //hxf-0803-文件busid
    busId: {
      type: String,
      default: () => ''
    },
    // hxf-0903-模块id
    modelType: {
      type: String,
      default: () => ''
    },
    //hxf-0803-是否显示后台返回文件列表
    isShowFileList: {
      type: Boolean,
      default: () => {
        return true
      }
    },//hxf-0803-是否显示后台返回文件列表
    isView: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    //hxf-0803-文件列表
    propsFileList: {
      type: Array,
      default: () => []
    },
    // 自动加载文件
    autoLoadFiles: {
      type: Boolean,
      default: true
    },
    // 隐藏说明文字
    hideExplain: {
      type: Boolean,
      default: false
    },
    // 是否支持删除
    canDelete: {
      type: Boolean,
      default: false
    }
  },
  created () {
    // hxf-0903-各类文件可支持扩展名
    this.typeArr = this.type.split(',')
    this.type.split(',').map(item => {
      if (item === 'image') {
        this.accepts[0] = '.jpg,.jpeg,.png,.gif,.bmp'
        this.tips[0] = '上传图片：支持扩展名：jpg、jpeg、png、gif、bmp'
      } else if (item === 'video') {
        this.accepts[1] = '.wmv,.mpeg,.mp4'
        this.tips[1] = '上传视频：支持扩展名：wmv、mpeg、mp4'
      } else {
        this.accepts[2] = '.jpg,.jpeg,.png,.gif,.bmp,.wmv,.mpeg,.mp4,.doc, .docx, .xls, .xlsx, .ppt, .pptx, .txt, .pdf'
        this.tips[2] = '上传文件：支持拓展名：rar、doc、docx、pdf、jpg、png...'
      }
    })
  },
  computed: {
    //hxf-0801-修改文件自定义支持扩展名
  },
  data () {
    return {
      // hxf-0903-文件列表
      fileList: [],
      // hxf-0903-视频文件列表
      videoList: [],
      // hxf-0903-图片文件列表
      imageList: [],
      // hxf-0903-存放上传文件
      formData: {},
      // hxf-0903-文件展示列表
      loadFileList: [],
      /*url1: 'http://static.oschina.net/uploads/img/201410/10134756_IFOl.png',
      url1: '',
      srcList: [
          // 'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg'
      ],*/
      // hxf-0903-PDF分页信息
      pageNum: 1,
      pageTotalNum: 1,
      pageRotate: 0,
      loadedRatio: 0,
      curPageNum: 0,
      // hxf-0903-PDF是否显示
      pdfDialogVisible: false,
      // hxf-0903-PDF文件路劲
      pdfSrc: '',
      dialogImageUrl: '',
      // hxf-0903-弹框是否展示
      dialogVisible: false,
      // hxf-0903-提示扩展名
      tips: [],
      accepts: [],
      // hxf-0903-上传组类型，type可以选择传多个类型，就会展示多个上传组件，不用多次引入
      typeArr: [],
    }
  },
  mounted () {
    // console.log(this.type.split(','))
    // hxf-0903-如果有busId则自动调用文件列表
    if (this.busId && this.autoLoadFiles) {
      getFiles(this.busId, this.modelType).then(resp => {
        if (resp.data.code === 0) {
          this.loadFileList = [...resp.data.data]
          this.$emit('loadCompleted', resp.data.data)
          // console.log( this.loadFileList)
          /*this.loadFileList.map(item => {
              // console.log('item----', item.fileId)
              // this.url1 = '/admin/sys-file/imgAbbreviation/' + item.fileId
              this.url1 = '/admin/sys-file/img/' + item.fileId
              this.srcList.push('/admin/sys-file/imgclear + item.fileId)
          })*/
        } else {
        }
      })
    }
  },
  methods: {
    // hxf-0903-如果有busId则手动调用文件列表，当busId从后端接收，自动获取不到列表时，手动调用一次该方法
    getFiles (busId) {
      if (busId) {
        getFiles(busId, this.modelType).then(resp => {
          if (resp.data.code === 0) {
            this.loadFileList = [...resp.data.data]
            this.$emit('loadCompleted', resp.data.data)
            // console.log('this.loadFileList---', this.loadFileList)
            /*this.loadFileList.map(item => {
                // console.log('item----', item.fileId)
                // this.url1 = '/admin/sys-file/imgAbbreviation/' + item.fileId
                this.url1 = '/admin/sys-file/img/' + item.fileId
                this.srcList.push('/admin/sys-file/img/' + item.fileId)
            })*/
          } else {
          }
        })
      }
    },
    // hxf-0903-文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange (file, fileList, type) {
      // console.log(file)
      if (type === 'image') {
        this.imageList = fileList;
      } else if (type === 'video') {
        this.videoList = fileList;
      } else {
        this.fileList = fileList;
      }
      this.propsFileList.push(file)
    },
    // hxf-0903-文件列表移除文件
    handleRemove (file) {
      this.typeArr.map(item => {
        if (item === 'image') {
          this.imageList = this.imageList.filter(item => item.uid !== file.uid)
        } else if (item === 'video') {
          this.videoList = this.videoList.filter(item => item.uid !== file.uid)
        } else {
          this.fileList = this.fileList.filter(item => item.uid !== file.uid)
        }
      })
      // this.fileList = this.fileList.filter(item => item.uid !== file.uid)
      let index = this.propsFileList.findIndex(item => item.uid === file.uid)
      this.propsFileList.splice(index, 1)
    },
    //hxf-0801-上传请求之前校验处理
    beforeUpload (file) {
      /* this.loadAction('文件上传中...')
       this.$emit('beforeUpload', file)
       let fileName = file.name,
       lastIndex = fileName.lastIndexOf('.'),
       suffix = fileName.substring(lastIndex, fileName.length)

       // console.log('suffix', this.constant.FILE_LIMIT.indexOf(suffix))
       if(this.constant.FILE_LIMIT.indexOf(suffix) === -1){
           this.$message({
               message: `文件上传暂不支持${suffix}格式！`,
               type: 'warning'
           })
           return false
       }
       // console.log('this.fileSize', this.fileSize)
       let isLt2M = file.size / 1024 / 1024 < this.fileSize
       if(!isLt2M) {
           this.$message({
               message: `上传文件大小不能超过 ${this.fileSize}MB!`,
               type: 'warning'
           });
       }*/
      return true
    },
    // hxf-0903-文件上传前校验
    checkFile (files, type) {
      let flag = false
      return new Promise((resolve, reject) => {
        outer:
        for (let i = 0; i < files.length; i++) {
          let fileName = files[i].name,
            lastIndex = fileName.lastIndexOf('.'),
            suffix = fileName.substring(lastIndex, fileName.length)
          if (!((files[i].size / 1024 / 1024) < this.fileSize)) {
            this.$message({
              type: 'error',
              message: `上传文件大小不能超过 ${this.fileSize}MB!`,
            });
            flag = true
            continue outer;
          }
          inter:
          switch (type) {
            case 'image':
              if (IMAGE_LIMIT.indexOf(suffix) === -1) {
                this.$message({
                  type: 'error',
                  message: `图片上传暂不支持${suffix}格式！`,
                });
                flag = true
                continue outer;
              }
              break;
            case 'video':

              if (VIDEO_LIMIT.indexOf(suffix) === -1) {
                this.$message({
                  type: 'error',
                  message: `视频上传暂不支持${suffix}格式！`,
                });
                flag = true
                continue outer;
              }
              break;
            default:
              if (FILE_LIMIT.indexOf(suffix) === -1) {
                this.$message({
                  type: 'error',
                  message: `文件上传暂不支持${suffix}格式！`,
                });
                flag = true
                continue outer;
              }
          }
        }
        setTimeout(function () {
          resolve(!flag)
        }, 100)

      })

    },
    //hxf-0801-提交
    submit (module, busId) {

      // this.$set(this.formData, 'Authorization', this.headers.Authorization)
      // this.$set(this.formData, 'jsonBean', form)
      // this.$set(this.formData, 'file', this.fileList)

      // this.$refs.myUpload.submit()
      // 判断文件是否合法
      const video = new Promise((resolve, reject) => {
        this.checkFile(this.videoList, 'video').then(resp => {
          if (resp) resolve();
        })
      })
      const image = new Promise((resolve, reject) => {
        this.checkFile(this.imageList, 'image').then(resp => {
          if (resp) resolve();
        })
      })
      const file = new Promise((resolve, reject) => {
        this.checkFile(this.fileList, 'file').then(resp => {
          if (resp) resolve();
        })
      })

      Promise.all([video, image, file]).then(() => {
        this.loadAction('文件上传中...')
        try {
          let formData = new FormData();  //  用FormData存放上传文件
          this.propsFileList.forEach(file => {
            // console.log('-------------file', file)
            formData.append(this.uploadName, file.raw)
          })
          formData.append('module', module)
          if (busId) {
            formData.append('busId', busId)
          }
          this.http.post('/admin/sys-file/upLodeFileAdd', formData).then(resp => {
            // console.log('-------------', resp)
            if (resp.data.code === 0) {
              this.onSuccess(resp.data, null, this.propsFileList)
            } else {
              this.onError(resp.data, null, this.propsFileList)
            }
          })
        } catch (e) {
          console.log(e)
          this.onError(e)
        }

      })
    },
    //hxf-0801-提交成功
    onSuccess (response, file, fileList) {
      this.loadClose()
      this.fileList = []
      this.imageList = []
      this.videoList = []
      this.$emit('onSuccess', response, file, fileList)
    },
    //hxf-0801-提交失败
    onError (err, file, fileList) {
      this.loadClose()
      this.$message({
        type: 'error',
        message: '上传失败！'
      })
      this.$emit('onError', err, file, fileList)
    },
    // hxf-0903-删除文件
    deleteLoadFile (item) {
      // this.$emit('handleClean', item)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delFiles(item.fileId, this.modelType).then(resp => {
          if (resp.data.code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // if (this.loadFileList.length > 0) {
            //     let index = this.loadFileList.findIndex(e => e.fileId === item.fileId)
            //     this.loadFileList.splice(index, 1)
            // }
            this.getFiles(this.busId)
            // this.loadFileList = [];
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // hxf-0903-下载文件
    downloadLoadFile (item) {
      checkFiles(item.fileId).then(resp => {
        if (resp.data.code === 0) {
          // window.open('/admin/sys-file/download/' + item.fileId)
          // window.open('/admin/sys-file/downloadAbbreviation/' + item.fileId)
          download('/admin/sys-file/download/' + item.fileId, null).then(response => {
            downloadBlob(response.data, item.original)
          })
        } else {
          this.$message({
            message: `文件不存在！`,
            type: 'warning'
          })
        }
      })
    },
    numPages (number) {
      console.log('numPages', number)
    },
    // hxf-0903-当文件是PDF时预览
    viewPdf (item) {
      console.log(item)
      // 根据后台返回的地址设置
      this.pdfSrc = item.fileId
      this.pdfDialogVisible = true
    },
    // hxf-0903-弹框X关闭
    beforeClose (done) {
      done()
    },
    // hxf-0903-图片大图查看
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 清除预览的文件
    clear () {
      this.loadFileList.length = 0
      this.fileList.length = 0
      this.videoList.length = 0
      this.imageList.length = 0
      this.formData.length = 0
    }
  }
}
</script>

<style scoped lang='scss'>
.img-box {
  width: 100px;
  height: 100px;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
}

.upload-text {
  width: 102px;
  height: 32px;
  color: $theme-color;
  border: 1px solid $theme-color;
}
</style>

